package com.hw.common.utils.log;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hw.common.utils.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuhao
 * @date 2022-05-14 15:22
 */
@Component
@Slf4j
public class LogUtil {

    /**
     * 请求信息写入日志 控制器中使用
     * @param joinPoint
     */
    public static void writeRequestLog(JoinPoint joinPoint){
        HttpServletRequest request = ServletUtil.getRequest();
        log.info("请求地址url={}",request.getRequestURL());
        log.info("请求类型method={}",request.getMethod());
        log.info("客户端ip={}",request.getRemoteAddr());
        if (joinPoint != null){
            log.info("调用类和方法名class_method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());

            log.info("请求参数={}", JSONUtil.toJsonStr(joinPoint.getArgs()));

        }
        try {
            log.info("头信息header:{}",  JSONUtil.toJsonStr(LogUtil.getHeaderInfo(request)));
        } catch (Exception e) {
            log.info("发起请求的页面地址referer={}",request.getHeader("Referer"));
            log.info("客户端标识user-agent={}", request.getHeader("User-Agent"));
        }
        try {
            log.info("GET参数requestParams={}", JSONUtil.toJsonStr(request.getParameterMap()));
        } catch (Exception e) {
        }
    }

    /**
     * 请求信息写入日志 网关用
     * @param request
     */
    public static void writeRequestLog(ServerHttpRequest request){
        log.info("请求地址url={}", request.getPath());
        log.info("请求类型method={}", request.getMethod());
        log.info("客户端ip={}", request.getRemoteAddress());
        log.info("GET参数queryString:{}", request.getQueryParams());
        try {
            log.info("头信息header:{}",  JSONUtil.toJsonStr(request.getHeaders()));
        } catch (Exception e) {
            log.info("发起请求的页面地址referer={}",request.getHeaders().get("Referer"));
            log.info("客户端标识user-agent={}", request.getHeaders().get("User-Agent"));
        }
        try {
            log.info("请求体requestBody={}", JSONUtil.toJsonStr(request.getBody()));
        } catch (Exception e) {
        }
    }

    /**
     * 获取请求头信息
     * @param request
     * @return
     */
    public static Map<String, String> getHeaderInfo(HttpServletRequest request){
        Map<String, String> map = new HashMap<>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
